package com.ybkj.daijia.server.controller;

import com.ybkj.daijia.serverUtils.ExcelUtil;
import com.ybkj.daijia.ServiceSetting;
import com.ybkj.daijia.serverUtils.ServiceUtil;
import com.ybkj.daijia.common.Principal;
import com.ybkj.daijia.common.Result;
import com.ybkj.daijia.config.SalesApi;
import com.ybkj.daijia.server.exception.NoPermissionException;
import com.ybkj.daijia.page.Page;
import com.ybkj.daijia.server.errand.OrderType;
import com.ybkj.daijia.server.event.model.OperationLogEvent;
import com.ybkj.daijia.server.mc.Passenger;
import com.ybkj.daijia.server.model.Company;
import com.ybkj.daijia.server.sales.Activity;
import com.ybkj.daijia.server.sales.ActivityCouponRule;
import com.ybkj.daijia.server.sales.Coupon;
import com.ybkj.daijia.server.sales.CouponRule;
import com.ybkj.daijia.server.service.ActivityService;
import com.ybkj.daijia.server.service.CompanyService;
import com.ybkj.daijia.server.service.CouponRuleService;
import com.ybkj.daijia.server.service.CouponService;
import com.ybkj.daijia.server.service.ErrandUpService;
import com.ybkj.daijia.server.service.MemberAccountService;
import com.ybkj.daijia.server.service.MemberService;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author Shine
 */
@Controller
@RequestMapping(value = "couponrule")
public class CouponRuleController {


    @Autowired
    private CouponRuleService couponRuleService;

    @Autowired
    private MemberService memberService;

    @Autowired
    private CompanyService companyService;

    @Autowired
    private CouponService couponService;

    @Autowired
    private MemberAccountService memberAccountService;

    @Autowired
    private SalesApi salesApi;

    @Autowired
    private ActivityService activityService;

    @Autowired
    private ApplicationEventMulticaster applicationEventMulticaster;

    @Autowired
    private ErrandUpService errandService;

    @RequestMapping(value = "list", method = RequestMethod.GET)
    public ModelAndView list() {

        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("couponrule")) {
            ModelAndView mv = new ModelAndView();
            mv.setViewName("couponrule/list");

            return mv;
        } else {
            throw new NoPermissionException();
        }
    }

    @RequestMapping("listData")
    public @ResponseBody
    Page<CouponRule> listData() {

        Subject subject = SecurityUtils.getSubject();
        if (subject.isPermitted("couponrule")) {
            Page<CouponRule> result = couponRuleService.queryCouponRule();

            return result;
        } else {
            throw new NoPermissionException();
        }

    }


    @RequestMapping(value = "add", method = RequestMethod.GET)
    public ModelAndView add() {

        Subject subject = SecurityUtils.getSubject();

        Principal principal = (Principal) subject.getPrincipal();

        if (subject.isPermitted("couponrule")) {
            ModelAndView mv = new ModelAndView();
            List<Company> companys = companyService.findAll();
            ServiceSetting serviceSetting = ServiceUtil.checkOpen();
            if (serviceSetting.isPaotui()) {
                //根据公司id查询公司
                Company company = companyService.findOne(principal.getCompanyId());
                List<OrderType> errandTypeList = new ArrayList<OrderType>();
                errandTypeList = errandService.queryOrderType(principal.getCompanyId());
                mv.addObject("errandTypeList", errandTypeList);
            }
            mv.addObject("companys", companys);

            mv.setViewName("couponrule/add");

            return mv;
        } else {
            throw new NoPermissionException();
        }

    }

    /**
     * 创建优惠券规则
     *
     * @param title     标题
     * @param code      编码
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @param type
     * @param discount
     * @param money
     * @param number
     * @param eachLimit
     * @return
     */
    @RequestMapping("createCouponRule")
    public @ResponseBody
    Result<CouponRule> createCouponRule(
        @RequestParam(required = false, value = "title") String title,
        @RequestParam(required = false, value = "code") String code,
        @RequestParam(required = false, value = "startTime") String startTime,
        @RequestParam(required = false, value = "endTime") String endTime,
        @RequestParam(required = false, value = "type") Integer type,
        @RequestParam(required = false, value = "couponType") String couponType,
        @RequestParam(required = false, value = "couponTypeId") Long couponTypeId,
        @RequestParam(required = false, value = "discount") Double discount,
        @RequestParam(required = false, value = "money") BigDecimal money,
        @RequestParam(required = false, value = "number") Integer number,
        @RequestParam(required = false, value = "eachLimit") Integer eachLimit) {
        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();
        Result<CouponRule> result = new Result<CouponRule>();
        result.setSuccess(false);

        if (subject.isPermitted("couponrule")) {
            Date start = null;
            Date end = null;
            if (type == 1) {
                int r = money.compareTo(BigDecimal.ZERO); //和0，Zero比较
                if (r == -1 || number < 0 || eachLimit < 0) {

                    result.setMessage("参数不合法");
                    return result;
                }
            }

            if (!StringUtils.isEmpty(startTime)) {

                try {
                    start = DateUtils.parseDate(startTime, "yyyy-MM-dd");

                } catch (ParseException e) {
                    e.printStackTrace();
                }

            }

            if (!StringUtils.isBlank(endTime)) {

                try {
                    end = DateUtils.parseDate(endTime, "yyyy-MM-dd");

                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }

            result = couponRuleService
                .insert(title, code, start, end, principal.getCompanyId(), type, couponType,
                    couponTypeId, discount, money, number, eachLimit);

            return result;
        } else {
            result.setMessage("您没有该权限");
            return result;
        }

    }

    @RequestMapping(value = "delete", method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> deleteData(Long id) throws ParseException {

        Subject subject = SecurityUtils.getSubject();
        if (subject.isPermitted("couponrule")) {
            Map<String, Object> map = new HashMap<String, Object>();
            Result<ActivityCouponRule> result = salesApi.findByCoupon(id);
            List<ActivityCouponRule> list = result.getData();
            if (!CollectionUtils.isEmpty(list)) {
                for (ActivityCouponRule activityCouponRule : list) {
                    Activity activity = activityService.findOne(activityCouponRule.getActivityId());
                    if (!activity.isStoped() && !activity.getTimeStatus()
                        .equals(Activity.ACTIVITY_STATUS_OVERDUE)) {
                        map.put("success", false);
                        map.put("message", "无法删除，有活动正在使用此优惠券规则（请先删除或停止相关活动）");
                        return map;
                    }
                }
            }
			
			
			
			
			
			
			
			/*Result<Activity> result = salesApi.findValidByEvent(null);
			List<Activity> list = result.getData();
			for (Activity activity : list) {
				List<ActivityCouponRule> list2 = salesApi.findByActivity(activity.getId()).getData();
				for (ActivityCouponRule activityCouponRule : list2) {
					if(activityCouponRule.getCouponRuleId().equals(id)){
						
					}
				}
			}*/

            Integer i = couponRuleService.deleteCouponRule(id);
            if (i == 0) {
                map.put("success", true);
                map.put("message", "删除成功");
            } else {
                map.put("success", false);
                map.put("message", "删除失败");
            }
            return map;
        } else {
            throw new NoPermissionException();
        }

    }
	
	
/*	@RequestMapping(value="invalidCoupon",method=RequestMethod.POST)
	public @ResponseBody Result<Integer> invalidCoupon(Long id){
		
		Subject subject = SecurityUtils.getSubject();
		Principal principal = (Principal) subject.getPrincipal();
		
		if(subject.isPermitted("couponrule")){
			Result<Integer> result = new Result<Integer>();
			
			if(null != id){
				Coupon coupon = couponService.findOne(id);
				if(null != coupon){
					
					String detail="【%s】使优惠劵【"+coupon.getCode()+"】失效";
					
					coupon.setStatus(Coupon.COUPON_STATUS_INVALID);
					couponService.update(coupon);
					
					OperationLogEvent operationLogEvent = new OperationLogEvent(principal,detail);
					applicationEventMulticaster.multicastEvent(operationLogEvent);
					
					result.setSuccess(true);
					result.setMessage("操作成功");
				}else{
					result.setMessage("没有可以操作的数据");
				}
			}else{
				result.setMessage("没有可以操作的数据");
			}
			
			return result;
		}
		else{
			throw new NoPermissionException();
		}
	}*/

    @RequestMapping("invalidCouponData")
    public @ResponseBody
    Result<Coupon> invalidCouponData(Long id) throws ParseException {

        Subject subject = SecurityUtils.getSubject();

        Result<Coupon> result = new Result<Coupon>();
        result.setSuccess(false);

        if (subject.isPermitted("couponrule")) {
            if (id != null) {
                result = couponService.updateCouponLapsed(id);
            } else {
                result.setMessage("没有可以操作的数据");
            }
        } else {
            result.setMessage("您没有该权限");
        }
        return result;

    }


    @RequestMapping(value = "lapsed", method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> lapsedData(Long id) throws ParseException {

        Subject subject = SecurityUtils.getSubject();
        if (subject.isPermitted("couponrule")) {
            Map<String, Object> map = new HashMap<String, Object>();
            Integer i = couponRuleService.updateCouponRuleLapsed(id);
            if (i == 0) {
                map.put("success", true);
                map.put("message", "操作成功");
            } else {
                map.put("success", false);
                map.put("message", "没有可以操作的数据");
            }
            return map;
        } else {
            throw new NoPermissionException();
        }

    }


    @RequestMapping(value = "coupon/{id}", method = RequestMethod.GET)
    public ModelAndView coupon(@PathVariable("id") Long id,
        @RequestParam(required = false, value = "couponCode") String couponCode,
        @RequestParam(required = false, value = "phone") String phone) {

        Subject subject = SecurityUtils.getSubject();
        if (subject.isPermitted("couponrule")) {

            ModelAndView mv = new ModelAndView();
            mv.setViewName("couponrule/couponlist");
            mv.addObject("couponRule", couponRuleService.findOne(id));

            return mv;
        } else {
            throw new NoPermissionException();
        }
    }

    @RequestMapping("couponData")
    public @ResponseBody
    Page<com.ybkj.daijia.server.sales.Coupon> couponData(Long id,
        @RequestParam(required = false, value = "couponCode") String couponCode,
        @RequestParam(required = false, value = "phone") String phone) {

        Subject subject = SecurityUtils.getSubject();
        if (subject.isPermitted("couponrule")) {

            Page<Coupon> result = couponService.queryCoupon(id, couponCode, phone);
            if (result.getTotalElements() > 0) {
                DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                for (Coupon coupon : result.getContent()) {
                    coupon.setCreatedStr(format.format(coupon.getCreated()));
                    if (null != coupon.getPassengerId()) {
                        Passenger passenger = memberService
                            .findOnePassenger(coupon.getPassengerId());
                        if (passenger != null) {
                            coupon.setPassenger(passenger);
                        }
                    }
                }
            }
            return result;
        } else {
            throw new NoPermissionException();
        }

    }


    @RequestMapping(value = "mass/{id}", method = RequestMethod.GET)
    public ModelAndView couponMP(@PathVariable("id") Long id) {

        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("couponrule")) {
            ModelAndView mv = new ModelAndView();
            mv.setViewName("couponrule/mass");

            mv.addObject("couponRule", couponRuleService.findOne(id));

            return mv;
        } else {
            throw new NoPermissionException();
        }
    }

    @RequestMapping(value = "mass", method = RequestMethod.POST)
    public String mass(Long couponRuleId, Integer amount) {

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();

        if (subject.isPermitted("couponrule")) {

            CouponRule couponRule = couponRuleService.findOne(couponRuleId);

            if (null != couponRuleId && null != amount && amount > 0) {

                couponService.listMass(couponRuleId, amount);

                String detail = "【%s】批量生成优惠劵【" + couponRule.getTitle() + "】" + amount + "张";
                OperationLogEvent operationLogEvent = new OperationLogEvent(principal, detail);
                applicationEventMulticaster.multicastEvent(operationLogEvent);
            }

            return "redirect:coupon/" + couponRuleId;
        } else {
            throw new NoPermissionException();
        }

    }
//	@RequestMapping(value="mass",method=RequestMethod.POST)
//	public String mass(@RequestParam(required = false, value = "couponRuleId") Long couponRuleId,
//                       @RequestParam(required = false, value = "param") String param){
//
//		Subject subject = SecurityUtils.getSubject();
//		Principal principal = (Principal) subject.getPrincipal();
//
//		if(subject.isPermitted("couponrule")){
//
//			CouponRule couponRule=couponRuleService.findOne(couponRuleId);
//			Integer count = 0;
//			if(null!=couponRuleId ){
//			    if(null != param) {
//                    JSONObject paramJson = JSON.parseObject(param);
//                    List<JSONObject> jsonList = (List) paramJson.get("param");
//                    for (JSONObject json : jsonList) {
//                        count += Integer.parseInt(json.get("couponNumber").toString().trim());
//                    }
//                    couponService.listMass(couponRuleId, param);
//					System.out.println("param：" +param);
//                    String detail="【%s】批量生成优惠劵【"+couponRule.getTitle()+"】"+count+"张";
//                    OperationLogEvent operationLogEvent = new OperationLogEvent(principal,detail);
//                    applicationEventMulticaster.multicastEvent(operationLogEvent);
//                }
//			}
//			return "redirect:/couponrule/coupon/"+couponRuleId;
//		}
//		else{
//			throw new NoPermissionException();
//		}
//
//	}

    @RequestMapping(value = "export/{id}", method = RequestMethod.GET)
    public void export(@PathVariable("id") Long id, HttpServletRequest req,
        HttpServletResponse response) throws IOException {

        Subject subject = SecurityUtils.getSubject();

        List<com.ybkj.daijia.server.sales.Coupon> list = couponService.findAll(id);

        if (subject.isPermitted("couponrule")) {

            String[] heards = {"编码", "密码", "使用状态", "客户称呼/手机号", "客户类型"};

            List<List<String>> rowlist = new ArrayList<List<String>>();

            for (com.ybkj.daijia.server.sales.Coupon c : list) {

                List<String> celllist = new ArrayList<String>();

                if (c.getCode() == null) {
                    celllist.add("");
                } else {
                    celllist.add(c.getCode());
                }

                if (c.getCodeKey() == null) {
                    celllist.add("");
                } else {
                    celllist.add(c.getCodeKey());
                }

                if (c.getStatus() == 0) {
                    celllist.add("未绑定");
                } else if (c.getStatus() == 1) {
                    celllist.add("未使用");
                } else if (c.getStatus() == 2) {
                    celllist.add("已使用");
                } else {
                    celllist.add("已失效");
                }

                if (c.getPassengerId() == null) {
                    celllist.add("");
                    celllist.add("");
                } else {
                    Passenger passenger = memberService.findOnePassenger(c.getPassengerId());
                    if (null != passenger) {
                        if (null == passenger.getPhone()) {
                            celllist.add(passenger.getName() + "/" + "无");
                        } else {
                            celllist.add(passenger.getName() + "/" + passenger.getPhone());
                        }
                        celllist.add(passenger.getTypeStr());
                    }
                }

                rowlist.add(celllist);
            }

            ExcelUtil.export(req, response, heards, rowlist);

        } else {
            throw new NoPermissionException();
        }

    }


    @org.springframework.web.bind.annotation.InitBinder
    public void InitBinder(WebDataBinder dataBinder) {

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        dateFormat.setLenient(false);
        dataBinder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));

    }
}

